package com.itheima.controller.v1;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.itheima.common.PageResult;
import com.itheima.common.R;
import com.itheima.controller.v1.api.EasyExcelContrllerApi;
import com.itheima.pojo.TbClue;
import com.itheima.service.TbClueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/excel")
@RestController
public class EasyExcelController implements EasyExcelContrllerApi {

    @Autowired
    private TbClueService tbClueService;

    //下载excel模板
    @GetMapping("/download")
    @Override
    public void easyExcelDownload(HttpServletResponse response) throws IOException {

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=download_modle.xlsx");

        EasyExcel.write(response.getOutputStream(), TbClue.class).sheet("模板").doWrite(getData());
    }


    //文件上传
    @PostMapping("/upload")
    @Override
    public R easyExcelUpload(@RequestParam("file") MultipartFile file) throws IOException {
        List<TbClue> list=new ArrayList<>();
        EasyExcel.read(file.getInputStream(), TbClue.class,new AnalysisEventListener<TbClue>() {
            //解析输入数据为指定对象格式
            @Override
            public void invoke(TbClue data, AnalysisContext context) {
                list.add(data);
            }
            //解析完成
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                System.out.println("解析完成");
            }
        }).sheet().doRead();
        for (int i = 0; i < list.size(); i++) {
            System.err.println("批量添加线索"+i+":"+list.get(i));
            tbClueService.add(list.get(i));
        }
        return R.success("上传文件批量添加线索成功",list);
    }

    private List getData() {
        List<TbClue> list =new ArrayList<>();
        TbClue tbClue=new TbClue();
        list.add(tbClue);
        return list;
    }
}
